﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DHQGHN.DAL.BO.Admin;
using DHQGHN.Common;
using DHQGHN.DAL.Common;
using DHQGHN.PM0.Models.Admin;
using DHQGHN.PM0.Controllers;
using DHQGHN.PM0.Common.Attributes;
using DHQGHN.MVC.Controllers;

namespace DHQGHN.PM0.Controllers.Admin
{
    public class GroupInRoleController : BaseController
    {
        GroupInRoleBO groupInRoleBO;
        log4net.ILog logger = log4net.LogManager.GetLogger(typeof(GroupInRoleController));

        public ActionResult Index(GroupInRoleModel m = null, int pageIndex = 0, string sort = "Id", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                SetActiveMenu("/GroupInRole/Index");
                if (m == null) m = new GroupInRoleModel();
                m.RoleID = -1;
                var model = search(m, pageIndex, currentId, false);
                ViewBag.lstApp = CommonData.getListApp("Chọn ứng dụng", "-1");
                ViewBag.lstRole = GetLableItem("Chọn vai trò", "-1");
                return View("~/Views/GroupInRole/GroupInRole.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Hiển thị form thêm mới nhóm người dùng
        [HttpPost]
        public ActionResult actionPrepareCreateOrUpdateGroupInRole(int? id, int roleID, int appID)
        {
            try
            {
                GroupInRoleModel model = null;
                if (roleID > -1)
                {
                    if (model == null)
                    {
                        model = new GroupInRoleModel()
                        {
                            GroupInRoleID = -1,
                            Descriptions = "",
                            IsActive = 1
                        };
                    }
                    ViewBag.lstApp = CommonData.getListApp("Chọn ứng dụng", "-1");
                    ViewBag.AppID = appID;
                    ViewBag.lstRole = getListRole();
                    ViewBag.lstGroup = getListActiveGroup(getListGroup(appID), getListGroupInRoleByRoleID(roleID));
                    if (Request.IsAjaxRequest())
                    {
                        return PartialView("~/Views/GroupInRole/_GroupInRoleModel.cshtml", model);
                    }
                }
                return View(model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [HttpPost]
        public ActionResult actionSearch(GroupInRoleModel aModel = null, int pageIndex = 0, string sort = "GroupInRoleId", string sortDir = "ASC", int currentId = -1)
        {
            try
            {
                if (aModel == null) aModel = new GroupInRoleModel();

                var model = search(aModel, pageIndex, currentId, false);
                ViewBag.lstRole = getListRole();
                ViewBag.roleID = aModel.RoleID.ToString();
                return PartialView("~/Views/GroupInRole/_GroupInRoleList.cshtml", model);
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        /// Thêm mới nhóm người dùng
        [HttpPost]
        [ValidateInput(false)]
        [AjaxValidateAntiForgeryToken]
        public ActionResult actionCreateOrUpdateGroupInRole(GroupInRoleModel model, int[] listID)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    groupInRoleBO = new GroupInRoleBO();
                    bool result = groupInRoleBO.createOrUpdateGroupInRole(model.toDALModel(), listID);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                           CommonData.AppName,
                           GetFunction(),
                           LogStream.GetJsonString<GroupInRoleModel>(model) +
                           CommonData.GetListId("Danh sách GroupId: ", ";", listID),
                           Resources.Localization.ActionSaveUpdateCaption + " - actionCreateOrUpdateGroupInRole");

                        if (model.GroupInRoleID > -1)
                        {
                            return Json(JsonResponse.Json200("Gán vai trò cho nhóm người dùng thành công!"));
                        }
                        else
                        {
                            return Json(JsonResponse.Json200("Gán vai trò cho nhóm người dùng thành công!"));
                        }
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        public JsonResult GetListRoleByApp(int AppId)
        {
            try
            {
                RoleBO roleBO = new RoleBO();
                var lstType = roleBO.GetListRoleByApp(AppId);
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.RoleId.ToString(),
                        Text = type.RoleName
                    });
                }

                return Json(new SelectList(lstItems, "Value", "Text"));
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        [AjaxValidateAntiForgeryToken]
        public ActionResult actionDelete(int[] id)
        {
            try
            {
                if (Request.IsAjaxRequest())
                {
                    groupInRoleBO = new GroupInRoleBO();
                    bool result = groupInRoleBO.deleteGroupInRole(id);
                    if (result)
                    {
                        LogStream.Write(GetCurrentUserName(),
                            CommonData.AppName,
                            GetFunction(),
                            CommonData.GetListId("Danh sách Id: ", ";", id),
                            Resources.Localization.ActionDeleteCaption + " - actionDelete");

                        return Json(JsonResponse.Json200("Xóa nhóm người dùng thành công!"));
                    }
                    else
                    {
                        return Json(JsonResponse.Json500("Xảy ra lỗi trong quá trình xử lý!"));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
            return null;
        }

        private DataPage<GroupInRoleModel> search(GroupInRoleModel myModel, int pageIndex, int currentId, bool compareEqual)
        {
            try
            {
                groupInRoleBO = new GroupInRoleBO();
                var models = new DataPage<GroupInRoleModel>();
                var DALModel = groupInRoleBO.GetDynamicListPaging(myModel.toDALModel(), PageSize, pageIndex);
                var lstItem = DALModel.Data;
                foreach (DHQGHN.DAL.Models.Admin.GroupInRoleModel m in lstItem)
                {
                    models.Data.Add(new GroupInRoleModel(m));
                }

                GroupInRoleModel model = null;
                if (currentId >= 0 && models.Data.Count > 0)
                {
                    model = models.Data.Find(groupInRole => groupInRole.GroupInRoleID == currentId);
                    models.CustomData = model;
                }
                else
                {
                    models.CustomData = myModel;
                }
                if (models.Data.Count > 0)
                {
                    //Tao component phan trang
                    var pagNative = new Pagination
                    {
                        ActionName = "actionSearch",
                        ModelName = "GroupInRole",
                        CurrentPage = pageIndex,
                        InputSearchId = string.Empty,
                        TagetReLoadId = "group-in-role-list",

                    };
                    pagNative.TotalRows = models.Data[0].RecordCount;
                    pagNative.CurrentRow = models.Data.Count;
                    ViewBag.Pagination = pagNative;
                }
                return models;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListRole()
        {
            try
            {
                RoleBO roleBO = new RoleBO();
                var lstType = roleBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "-1",
                    Text = "Chọn vai trò"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.RoleId.ToString(),
                        Text = type.RoleName
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        //Get all group in a role of database
        private Dictionary<int, int> getListGroupInRoleByRoleID(int roleID)
        {
            try
            {
                groupInRoleBO = new GroupInRoleBO();
                Dictionary<int, int> lstMenu = new Dictionary<int, int>();
                var lstItems = groupInRoleBO.GetAllGroupInRoleByRoleId(roleID);
                foreach (var group in lstItems)
                {
                    lstMenu.Add(group.GroupID, group.RoleID);
                }
                return lstMenu;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private List<GroupModel> getListGroup(int? AppId)
        {
            try
            {
                GroupBO groupBO = new GroupBO();
                var lstGroup = groupBO.GetAll(AppId);
                List<GroupModel> lstItems = new List<GroupModel>();
                foreach (var group in lstGroup)
                {
                    lstItems.Add(new GroupModel(group));
                }
                return lstItems;
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListActiveGroup(List<GroupModel> lstGroup, Dictionary<int, int> lstGroupInRole)
        {
            try
            {
                List<SelectListItem> lstItems = new List<SelectListItem>();
                foreach (var group in lstGroup)
                {
                    if (!lstGroupInRole.ContainsKey(group.GroupId))
                    {
                        lstItems.Add(new SelectListItem
                        {
                            Value = group.GroupId.ToString(),
                            Text = group.GroupName
                        });
                    }
                }
                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> getListApp()
        {
            try
            {
                ApplicationBO appBO = new ApplicationBO();
                var lstType = appBO.GetAll();
                List<SelectListItem> lstItems = new List<SelectListItem>();
                lstItems.Add(new SelectListItem
                {
                    Value = "-1",
                    Text = "Chọn ứng dụng"
                });
                foreach (var type in lstType)
                {
                    lstItems.Add(new SelectListItem
                    {
                        Value = type.AppId.ToString(),
                        Text = String.Concat(type.AppName, " - ", type.AppCode)
                    });
                }

                return new SelectList(lstItems, "Value", "Text");
            }
            catch (Exception ex)
            {
                logger.Error(ex.ToString());
                throw;
            }
        }

        private IEnumerable<SelectListItem> GetLableItem(string title, string value)
        {
            return new List<SelectListItem>{
                new SelectListItem {
                    Value = value,
                    Text = title
                }
            };
        }


        private string GetFunction()
        {
            return "Phân vai trò cho nhóm người dùng - GroupInRoleController";
        }
    }
}